package com.scs.application.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scs.application.core.query.*;
import com.scs.application.core.utils.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @description: 查询参数上下文解析器
 */
public class QueryContextInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!request.getMethod().equalsIgnoreCase(HttpMethod.GET.name())) {
            return true;
        }

        Page page = QueryGenerator.parsePage(request);

        QueryContext queryContext = QueryContextHolder.currentContext();
        queryContext.setPage(page);
        queryContext.setWrapper(new QueryWrapper());

        if (StringUtils.isBlank(request.getParameter(QueryGenerator.REQ_QUERY_CONDITIONS_NAME))
                && StringUtils.isBlank(request.getParameter(QueryGenerator.REQ_ORDER_CONDITIONS_NAME))) {
            return true;
        }

        List<QueryCondition> queryConditions = QueryGenerator.parseQueryConditions(request);
        List<OrderCondition> orderConditions = QueryGenerator.parseOrderConditions(request);
        QueryWrapper wrapper = QueryGenerator.initQueryWrapper(queryConditions, orderConditions);

        Map<String, Object> params = QueryGenerator.parseParams((queryConditions));

        queryContext.setWrapper(wrapper);
        queryContext.setParams(params);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        QueryContextHolder.clear();
    }
}
